#include "maindialog.h"
#include "ui_maindialog.h"
#include <QMessageBox>
#include <QRandomGenerator>


MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    m_mqtt = new QMqttClient(this);

    m_mqtt->setHostname("8.140.241.110");
    m_mqtt->setPort(1883);


    quint32 randomValue = QRandomGenerator::global()->generate();
    //qDebug() << randomValue;

    m_mqtt->setClientId(QString("qtclient_%1").arg(randomValue));

    connect(m_mqtt, &QMqttClient::connected, this, &MainDialog::onConnected);
    connect(m_mqtt, &QMqttClient::disconnected, this, &MainDialog::onDisconnected);
    connect(m_mqtt, &QMqttClient::messageReceived, this, &MainDialog::onMessageReceived);

    m_mqtt->connectToHost();  // 连接 MQTT Broker
}

MainDialog::~MainDialog()
{
    delete ui;
}


void MainDialog::onDisconnected()
{
    QMessageBox::critical(this, "提示", "连接 MQTT Broker 失败！");
}


void MainDialog::onConnected()
{
    qDebug() << "Connected to broker";

    // 订阅传感器主题
    auto subscription = m_mqtt->subscribe(QString("My_dogdoog/sensor/+"));
    if (!subscription) {
        qDebug() << "Failed to subscribe";
        return;
    }

    // 订阅设备状态主题
    subscription = m_mqtt->subscribe(QString("My_dogdoog/state/+"));
    if (!subscription) {
        qDebug() << "Failed to subscribe";
        return;
    }
}

void MainDialog::onMessageReceived(const QByteArray &message, const QMqttTopicName &topic)
{
    qDebug() << "Received message:" << message << "from topic:" << topic.name();

    if(topic.name() == "My_dogdoog/state/lamp")
    {
        if(message == "0")
        {
            ui->btnLampOn->setText("开 灯");
        }
        else if(message == "1")
        {
            ui->btnLampOn->setText("关 灯");
        }
    }

    if(topic.name() == "My_dogdoog/sensor/dht11")
    {
        QStringList th = QString::fromUtf8(message).split('_');

        ui->labelTemperature->setText(QString("教室温度：%1 ℃").arg(th[0]));
        ui->labelHumidity->setText(QString("教室湿度：%1 %RH").arg(th[1]));
    }
}


void MainDialog::on_btnLampOn_clicked()
{
    if(ui->btnLampOn->text() == "开 灯")
        m_mqtt->publish(QString("My_dogdoog/cmd"), "e");
    else if(ui->btnLampOn->text() == "关 灯")
        m_mqtt->publish(QString("My_dogdoog/cmd"), "f");
}


void MainDialog::on_btnFanOn_clicked()
{
    m_mqtt->publish(QString("My_dogdoog/smart_plug/cmd/1"), "a1");
}
